package io.xxx.omni.osc.sync

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.dateTimeFormatter
import io.xxx.omni.osc.common.toJSONObject
import io.xxx.omni.osc.common.toLocalDateTime
import io.xxx.omni.osc.domain.Document
import io.xxx.omni.osc.domain.PlatformIdentity
import org.springframework.stereotype.Component
import org.springframework.web.util.UriComponentsBuilder

/**
 * POS
 */
@Component
class PosPorter : GenericPageDocumentPorter(), PlatformIdentity.Pos {

    private val httpUrl = "http://POS-SERVER/orders/data"

    override fun getResponse(context: JobContext, pageNo: Int, hasTotal: Boolean): JSONObject {
        val (store, startTime, endTime) = context
        val url = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .queryParam("shopCode", store.id)
            .queryParam("startTime", startTime.format(dateTimeFormatter))
            .queryParam("endTime", endTime.format(dateTimeFormatter))
            .queryParam("pageNo", pageNo)
            .queryParam("pageSize", pageSize)
            .toUriString()

        val response = lbRestTemplate.getForObject(url, JSONObject::class.java)
        if (response!!.getInteger("code") != 0) {
            throwException(context, url, response)
        }
        return response.getJSONObject("data")
    }

    override fun getCount(context: JobContext, response: JSONObject): Int = response.getInteger("count")

    override fun buildDocuments(context: JobContext, response: JSONObject): List<Document> {
        val data = response
            .getJSONArray("list")
        return data.map {
            val value = it.toJSONObject()
            val sn = value.getString("id")
            val rsn = value.getString("original_order_id")
            val status = value.getString("status")
            val modified = value.getString("updated_time").toLocalDateTime()
            Document(sn, rsn, status, modified, value)
        }
    }
}